package org.fanjr.simplify.zk.server;

import java.util.Properties;

import org.apache.zookeeper.server.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

public class ZkServerBean implements DisposableBean {

	private static final Logger LOGGER = LoggerFactory.getLogger(ZkServerBean.class);

	private static final String CONF_PERFIX = "zookeeper.";

	private static final String CONF_PATH_KEY = CONF_PERFIX + "cfg_path";

	protected ZkServer zkServer;

	public ZkServerBean(Environment environment) {
		initZookeeperServer(environment);
	}

	protected void initZookeeperServer(Environment environment) {

		try {
			ServerConfig config = new ServerConfig();
			String confPath = getPropertiesValue(CONF_PATH_KEY, null, environment);
			if (null != confPath) {
				config.parse(confPath);
				zkServer = ZkServer.runFromConfig(config);
				return;
			}

			Properties properties = ZkPropertiesUtils.getZkProperties(CONF_PERFIX, environment);
			zkServer = ZkServer.runFromProperties(properties);
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info(
						"Zookeeper Server [127.0.0.1:" + zkServer.getZkServer().getClientPort() + "] started success!");
			}
		} catch (Exception e) {
			LOGGER.error("Zookeeper Server started error!", e);
			destroy();
		}
	}

	private String getPropertiesValue(String key, String def, Environment environment) {
		String val = System.getProperty(key);
		if (StringUtils.hasText(val)) {
			return val;
		}
		val = environment.getProperty(key);
		if (StringUtils.hasText(val)) {
			return val;
		}
		return def;
	}

	@Override
	public void destroy() {
		if (zkServer != null) {
			zkServer.destroy();
		}
	}

}
